package cn.aitstone.basic.service.impl;

import cn.aitstone.basic.constant.BaseConstants;
import cn.aitstone.basic.dto.LoginDto;
import cn.aitstone.basic.dto.TokenDto;
import cn.aitstone.basic.exception.BusinessException;
import cn.aitstone.basic.jwt.JwtUtils;
import cn.aitstone.basic.jwt.RsaUtils;
import cn.aitstone.basic.jwt.UserInfo;
import cn.aitstone.basic.service.ILoginService;
import cn.aitstone.basic.utils.AjaxResult;
import cn.aitstone.basic.utils.HttpUtil;
import cn.aitstone.basic.utils.MD5Utils;
import cn.aitstone.basic.utils.StrUtils;
import cn.aitstone.system.domain.Menu;
import cn.aitstone.system.mapper.MenuMapper;
import cn.aitstone.system.mapper.PermissionMapper;
import cn.aitstone.user.domain.Logininfo;
import cn.aitstone.user.domain.User;
import cn.aitstone.user.domain.Wxuser;
import cn.aitstone.user.dto.WxDto;
import cn.aitstone.user.mapper.LogininfoMapper;
import cn.aitstone.user.mapper.UserMapper;
import cn.aitstone.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
 * @Description: 登录相关实现类
 * @Author: Sheldon
 * @Version: 1.0
 * @Date:  2022/7/8 21:29
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPri;

    /**
    * @Title: account
    * @Description: 登录方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/9 22:14
    * @Parameters: [loginDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空");
        }
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        if(logininfo == null){
            throw new BusinessException("账户或者密码错误");

        }
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        return loginSuccessJwtHandler(logininfo);

    }

    public Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo){
        // 获取私钥进行加密
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(jwtRsaPri).getFile());
        System.out.println(privateKey);
        // 将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        // 根据Logininfo&menus&permissions加密之后得到JWT串
        UserInfo userInfo = new UserInfo();

        if (logininfo.getType() == 0){
            // 1.如果是后台用户那么需要设置菜单权限和按钮权限到userInfo中
            List<String> permissions = permissionMapper.loadOwnPermissionByLogininId(logininfo.getId());
            List<Menu> menus = menuMapper.loadOwnMenuByLogininfoId(logininfo.getId());
            userInfo.setPermissions(permissions);
            userInfo.setMenus(menus);
            map.put("permissions", permissions);
            map.put("menus", menus);
        }
        userInfo.setLogininfo(logininfo);
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);
        // 把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }


    /**
    * @Title:
    * @Description: token登录
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/14 17:26
    * @Parameters:
    * @Return
    */
   /* @Override
    public Map<String, Object> account(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空");
        }
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        if(logininfo == null){
            throw new BusinessException("账户或者密码错误");

        }
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号密码错误，请重新输入！");
        }
        // 生成UUID作为key
        String token = UUID.randomUUID().toString();
        // 将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        System.out.println(token);
        // 把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;
    }*/

    /**
    * @Title: sendMobileCode
    * @Description: 发送验证码方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/9 22:13
    * @Parameters: [loginDto]
    * @Return void
    */
    @Override
    public void sendCode(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String imageCodeKey = loginDto.getImageCodeKey();
        String codeValue = loginDto.getCodeValue();
        String type = loginDto.getType();
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(imageCodeKey) ||
                StringUtils.isEmpty(type) ||
                StringUtils.isEmpty(codeValue)) {
            throw new BusinessException("参数不能为空");
        }
        // 查询图形验证码是否正确
        Object imageCode = redisTemplate.opsForValue().get(imageCodeKey);
        if (imageCode == null) {
            throw new BusinessException("图形验证码已失效，请重新输入");
        }
        if (!imageCode.toString().equalsIgnoreCase(codeValue)) {
            throw new BusinessException("图形验证码错误，请重新输入");
        }
        // 判断账号是否存在
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        if (logininfo == null){
            throw new BusinessException("账号不存在，请重新输入");
        }
        // 根据不同的参数发送不同的信息
        String businessKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + username;
        if (username.indexOf("@") == -1) {
            // 获取验证码
            Object smsCode = getCode(businessKey);
            System.out.println("您的短信验证码是：" + smsCode);
        } else {
            // 获取验证码
            Object smsCode = getCode(businessKey);
            System.out.println("您的邮箱验证码是："+smsCode);
        }

    }

    /**
    * @Title: codeLogin
    * @Description: 通过验证码登录方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/9 22:12
    * @Parameters: [loginDto]
    * @Return cn.aitstone.basic.dto.TokenDto
    */
    @Override
    public TokenDto codeLogin(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();
        String type = loginDto.getType();
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空！");
        }
        Object code = redisTemplate.opsForValue().get(BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_KEY + username);
        // 判断能否成功获取到短信验证码【验证码失效或者电话号码不一致】
        if (code == null) {
            throw new BusinessException("验证码已失效，请重新输入");
        }
        // 判断短信验证码是否正确
        if (!code.equals(password)) {
            throw new BusinessException("验证码错误，请重新输入");
        }
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username, type);
        String token = UUID.randomUUID().toString();
        // 将敏感信息置空
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 将对象信息保存到redis
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        return new TokenDto(token, logininfo);
    }

    /**
    * @Title: wechat
    * @Description: 微信登录方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/10 17:24
    * @Parameters: [wxDto]
    * @Return cn.aitstone.basic.utils.AjaxResult
    */
    @Override
    public AjaxResult wechat(WxDto wxDto) {
        // 参数校验
        if(StringUtils.isEmpty(wxDto.getCode())){
            throw new BusinessException("参数不能为空");
        }

        String tokenUrl = BaseConstants.WechatConstant.TOKEN_URL
                .replace("APPID", BaseConstants.WechatConstant.APPID)
                .replace("SECRET", BaseConstants.WechatConstant.SECRET)
                .replace("CODE", wxDto.getCode());
        String jsonObjStr = HttpUtil.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(jsonObjStr);
        Wxuser wxuser = wxuserMapper.loadByOpenId(jsonObject.getString("openid"));
        if (wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            /*// 生成UUID作为key
            String token = UUID.randomUUID().toString();
            // 将uuid&&logininfo设置到redis中，设置30分钟有效期
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            // 把Logininfo对象的敏感信息置为空，作为value
            logininfo.setSalt("");
            logininfo.setPassword("");
            // 将uuid&&logininfo存入到map中，返回给前端
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);*/
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);

            return AjaxResult.me().setResultObj(map);

        }
        String paramStr = "?accessToken=" + jsonObject.getString("access_token") + "&openId=" + jsonObject.getString("openid");
        return AjaxResult.me().setSuccess(false).setMessage("nobinder").setResultObj(paramStr);


    }

    /**
    * @Title: binder
    * @Description: 微信绑定账号方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/10 19:31  
    * @Parameters: [wxDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> binder(WxDto wxDto) {
        // 参数校验
        String verifyCode = wxDto.getVerifyCode();
        String phone = wxDto.getPhone();
        String accessToken = wxDto.getAccessToken();
        String openId = wxDto.getOpenId();
        if (StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)){
            throw new BusinessException("参数不能为空");
        }
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        // 用户不存在：初始化user&logininfo并保存
        Logininfo logininfo = null;
        if (user == null){
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else {// 用户存在存在：查询Logininfo
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        // 根据前端传递的accessToken&openId查询微信用户基本信息
        String wxUserUrl = BaseConstants.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpUtil.httpGet(wxUserUrl);
        // 通过JSONObject方法将JSON字符串转换为指定对象
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        // 保存wxUser对象，并且需要设置userId字段为user对象的主键
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        // 返回成功登录map
        // 生成UUID作为key
       /* String token = UUID.randomUUID().toString();
        // 将uuid&&logininfo设置到redis中，设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 把Logininfo对象的敏感信息置为空，作为value
        logininfo.setSalt("");
        logininfo.setPassword("");
        // 将uuid&&logininfo存入到map中，返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;*/
        return loginSuccessJwtHandler(logininfo);
    }

    /**
    * @Title: logout
    * @Description: 退出登录
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/11 22:42
    * @Parameters: [token]
    * @Return void
    */
    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    /**
    * @Title: smsCodeDto2User
    * @Description: 初始化user对象信息
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/10 19:16  
    * @Parameters: [smsCodeDto]
    * @Return cn.aitstone.user.domain.User
    */
    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltpassword = MD5Utils.encrypByMd5(salt + "1");
        user.setSalt(salt);
        user.setPassword(saltpassword);
        return user;

    }

    /**
    * @Title: user2Logininfo
    * @Description: 将user对象拷贝到logininfo中
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/10 19:16  
    * @Parameters: [user]
    * @Return cn.aitstone.user.domain.Logininfo
    */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    /**
    * @Title: getCode
    * @Description: 生成验证码方法
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/9 22:13
    * @Parameters: [businessKey]
    * @Return java.lang.Object
    */
    private Object getCode(String businessKey) {
        Object smsCode = redisTemplate.opsForValue().get(businessKey);
        if (smsCode == null) {
            smsCode = StrUtils.getComplexRandomString(4);
        } else {
            // 获取过期时间
            Long expirationTime = redisTemplate.opsForValue().getOperations().getExpire(businessKey);
            if (expirationTime > 4 * 60) {
                throw new BusinessException("请一分钟之后再获取");
            }
        }
        redisTemplate.opsForValue().set(businessKey, smsCode, 5, TimeUnit.MINUTES);
        return smsCode;
    }
}
